<?php
namespace App\Repositories;

use App\Models\Activity;
use App\Models\ActivityFill;
use App\Models\Order;
use App\Models\Profit;
use App\Models\Income;
use App\Models\Member;
use App\Models\GroupPush;
use App\Models\ElectPool;
use App\Models\QrCode;
use App\Models\KeywordRecord;
use App\Models\AccountRecord;
use App\Models\MemberRecommend;
use App\Models\Superpick;
use App\Models\ElectPoolElected;
use App\Models\GroupJoin;

use App\Models\Parter;
use App\Models\ParterIncome;

use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;

use App\Repositories\RechargeComboRepository;
use App\Repositories\Api\MemberRepository;
use App\Repositories\Api\ActivityFillRepository;

use Exception;


class OrderRepository {

    public function getById($id = ''){
        return Order::where("id", "=", $id)->first();
    }

    public function getByOutTradeNo($out_trade_no){
        return Order::where("out_trade_no", "=", $out_trade_no)->first();
    }

    // 获取订单支付金额
    public function getTotalPriceById($order_id = 0)
    {
        if(!$order_id) return "";
        return Order::where("id", "=", $order_id)->value("total_price");
    }

    /**
     * 删除
     * @Author   thomashtao               bosslen
     * @DateTime 2021-11-08T22:42:14+0800
     * @param    string                   $order_id [description]
     */
    public function deleteOrder($order_id = "")
    {
        $order = Order::where("order_id", "=", $order_id)->find();
        if(!$order)
            throw new Exception("订单不存在");

        if($order['created_uid'] != UID)
            throw new Exception("无权限");

        Order::where("id","=", $order['id'])->update(['is_del' => 1]);
        return true;
    }

    /**
     * 修改金额
     * @Author   thomashtao               bosslen
     * @DateTime 2021-11-08T22:56:15+0800
     * @param    [type]                   $order_id [description]
     * @param    [type]                   $price    [description]
     */
    public function updatePrice($id, $price)
    {
        $order = Order::where("id", "=", $id)->find();

        if($order['created_uid'] != UID)
            throw new Exception("无权限");

        if($order['paid'])
            throw new Exception("订单已支付，不可修改");

        $res = Order::where("id", "=", $order['id'])->update(['total_price' => $price]);

        return $res;
    }

    public function updateOrder($trade_no="", $out_trade_no = "", $is_order=false, $pay_data = [])
    {
        if(!$out_trade_no) return ;
        if($is_order){
            $order = $this->getById($out_trade_no);
        }else{
            $order = $this->getByOutTradeNo($out_trade_no);
        }
        $order = $order->toArray();

        if(!$order || intval($order['status']) > 1) return  false;


        $data['status'] = 40;
        $data['flow_number'] = $trade_no;
        $data['pay_data'] = serialize($pay_data);
        $data['pay_time'] = date("Y-m-d H:i:s");

        Order::where("id", "=", $order['id'])->update($data);
        $memberRep = new MemberRepository();
        $rechargeRep = new RechargeComboRepository();

        $is_distribute = false;

        switch ($order['type']) {

            case 2://充值-服务号
                $recharge_total_price = $rechargeRep->get_recharge_total_amount($order['product_id']);
                $memberRep->change_user_account($order['uid'],null,null,5,$recharge_total_price,$order['id'],1);

                // $is_distribute = $this->_update_parter_income($order);  //更新推荐人的账户余额
                break;

            case 1://申请发帖
                $this->dikou_personal($order);//抵扣账户余额
                $this->insert_refund($order,$order['uid'],NULL,9);
                $member = $memberRep->getOne($order['product_id']);

                $price_data = unserialize($order['price_data']);
                $m_data['uid'] = $order['product_id'];
                $m_data['city'] = $pay_data['attach'];
                $m_data['sex'] = $member['gender']=='M' ? 1 : 2;
                $m_data['type'] = 2;
                $m_data['title'] = get_member_title($member);
                $m_data['desc'] = '遇见最美的爱情';
                $m_data['img'] = $member['avatar'];
                // $m_data['url'] = 'https://wx.bsbly.com/member/share?id='.md6($member['id']).'&from='.$pay_data['attach'];
                // $result = D('group_push')->saveOrUpdate($m_data);

                $m_data['create_time'] = date('Y-m-d H:i:s');
                GroupPush::insert($m_data);

                //增加微信通知模版 生成应征信息
                sendTemplateMsg($member['openid'], 10, [
                    'wo_uid'            => $member['id'],
                    'content'           => '你申请了公众号发帖',
                    'uid'               => $wo['id'],
                    'username'          => $wo['username'],
                    'df_uid'            => $df_account,
                    'page'              => "share/index?uid=" . $member['id']
                ], 11);

                break;

            default:
                break;
        }

        //奖励推荐人比例
        if(in_array($order['type'], array(7, 0)) && $order['total_price'] > 0){ //充值后返现
            $mr = MemberRecommend::where("uid","=", $order['uid'])->first();
            if(empty($mr)) return false;

            if(intval($mr['award_type']) == 0){  // 去掉只奖励联谊币
                return true;
            }

            $rm = Member::where("id", "=", $mr['ruid'])->first();
            if( !$rm ) return false; //用户不存在

            //获取推广人的消费返点比例
            $rmid = $rm['id'];
            $sp_award_rank = $rm['sp_award_rank'];
            //如果是线下活动，乘0.5
            if ($order['type'] == 0) {
                $sp_award_rank = $rm['sp_award_rank'] * 0.5;
            }
            $award_price = $order['total_price'] * $sp_award_rank;

            //增加推荐人奖励
            $rm_data['balance'] = $rm['balance'] + $award_price;
            $rm_data['total_award'] = $rm['total_award'] + $award_price;  //总收益
            $memberRep->updateFields($rm['id'], $rm_data);

            //增加奖励记录
            $order_type = order_type($order['type']);
            $in_data['price'] = $award_price;
            $in_data['uid'] = $rm['id'];
            $in_data['type'] = 1;
            $in_data['object_id'] = $order['uid'];
            $in_data['object_type'] = $order_type['key'];
            $in_data['create_time'] = date("Y-m-d H:i:s");
            Income::insert($in_data);

            if($is_distribute) return true;  //互选池分销过来的只奖励一级

            //二级返现
            $mr2 = MemberRecommend::where("uid","=", $rm['id'])->first();
            //二级不返现
            if(!empty($mr2)) return false;
            if(intval($mr2['award_type']) == 0){  // 去掉只奖励联谊币
                return true;
            }

            //ToDo  二级返现暂时不处理
            $rm2 = Member::where("id","=", $mr2['ruid'])->first();
            if(!$rm2) return false;

            //获取推广人的消费返点比例
            $rmid2 = $rm2['id'];
            $sp_award_rank2 = $rm2['sp_award_rank2'];

            //如果是线下活动，乘0.5
            if ($order['type']==0) {
                $sp_award_rank2 = $rm2['sp_award_rank2']*0.5;
            }
            $award_price2 = $order['total_price'] * $sp_award_rank2;

            //增加推荐人奖励
            $rm_data2['balance'] = $rm2['balance'] + $award_price2;
            $rm_data2['total_award'] = $rm2['total_award'] + $award_price2;  //总收益
            $memberRep->updateFields($rm2['id'], $rm_data);

            //增加奖励记录
            $order_type = order_type($order['type']);
            $in_data2['price'] = $award_price2;
            $in_data2['uid'] = $rm2['id'];
            $in_data2['type'] = 1;
            $in_data2['object_id'] = $order['uid'];
            $in_data2['object_type'] = $order_type['key'].'2';
            $in_data2['create_time'] = date("Y-m-d H:i:s");

            Income::insert($in_data2);
        }

        return true;
    }

    //超级心动
    public function updateSuperpick($superpick_id = 0, $superpick_price = 0.0)
    {
        if(!$superpick_id) return false;

        Superpick::where("id", "=", $superpick_id)->update([
            'is_superpick' => 1,
            'superpick_time' => date("Y-m-d H:i:s")
        ]);

        $superpick = Superpick::where("id", "=", $superpick_id)->first();
        $electpool = ElectPool::where("id","=",$superpick['elect_pool_id'])->first();

        $member1 = Member::where("id","=",$superpick['elect_uid'])->first();
        $member2 = Member::where("id","=",$superpick['elected_uid'])->first();

        // 增加微信通知模版 生成应征信息
        sendTemplateMsg($member2['openid'], 17, [
            'object_id'         => $superpick['id'],
            'object_type'       => 'superpick',
            'wo_uid'            => $member1['id'],
            'df_uid'            => $member2['id'],
            'content'           => $member1['id'].$member1['username'].'对你超级心动',
            'uid'               => $member1['id'],
            'username'          => $member1['username'],
            'elect_pool_title'  => $electpool['title'],
            'page'              => "elect-pool/elect?current=3&id=".$superpick['elect_pool_id']
        ], 13);

        (new MemberRepository())->change_user_account($member1['id'], $member2["id"],NULL,6,$superpick_price,NULL,0);

        return true;
    }

    public function generateOrder($data){

        if(!$data) return null;
        $data['uid'] = request()->get("wechat_admin_id");

        if(!$data['pay_type']){
            $data['pay_type'] = 'wx';
        }
        $data['data'] = json_encode($data['data']);

        if(!$data['out_trade_no']){
            $data['out_trade_no'] = date('YmdHis') . GenSecret(6,1) ;
        }

        return Order::create($data);
    }

    public function getLists($filter, $page=1, $limit=20, $just_amount = false, $field = false){
        !$field && $field = "id,order_id,type,pay_price,total_price,status,paid,product_id,add_time,pay_time";

        $model = Order::where($filter)->orderby("add_time","desc")
                ->cache(true)
                ->page($page, $limit)
                ->field($field);

        $filter['is_del'] = 0;

        if($just_amount){
            return $model->count("id");
        }

        $res =  $model->select();
        foreach ($res as $k => $v) {
            $res[$k]['add_time'] = date("Y-m-d H:i:s", $v['add_time']);
            $res[$k]['type_title'] = order_type($v['type']);
            $res[$k]['status_title'] = order_status($v['status']);
        }

        return $res;
    }

    private function after_pay_handle($order,$uid,$df_uid,$type){
        //账户余额<支付金额
        //账户余额=支付金额
        //账户余额>支付金额
        //账户余额
        $memberRep = new MemberRepository();
        $member  = $memberRep->getOne($order['uid']);
        //支付金额
        if($order['original_price']){
            $total_price = $order['original_price'];
        }else{
            $total_price = $order['total_price'];
        }
        $member['account'] = str_replace(',', '', $member['account']);
        if( $member['account'] <=  $total_price){//小于等于
            //扣除账户余额
            // Member::where("id","=", $order['uid'])->update(['account' => 0]);
            $memberRep->updateFields($order['uid'], ['account' => 0]);

            //记录account_record表详情
            $this->add_account_record($order,$uid,$df_uid,$type,$total_price);
        }elseif($member['account'] >  $total_price){//大于
            //扣除账户余额
            // Member::where("id","=", $order['uid'])->update(['account'=>bcsub($member['account'], $total_price,2)]);
            $memberRep->updateFields($order['uid'], ['account'=>bcsub($member['account'], $total_price,2)]);

            //记录account_record表详情
            $this->add_account_record($order,$uid,$df_uid,$type,$total_price);
        }
    }

    private function add_account_record($order, $uid, $df_uid, $type, $price){

        $mm = Member::where('id', "=", $uid)->first();

        //记录
        $rdata['uid'] = $uid;
        $rdata['unionid'] = $mm['unionid'];
        $rdata['df_uid'] = $df_uid;
        $rdata['type'] = $type;
        $rdata['orderid'] = !empty($order) ? $order['id'] : NULL;
        $rdata['inout'] = 0;
        $rdata['amount'] = $price;
        $rdata['remaining'] = str_replace(',', '', $mm['account']);//账户剩余

        return AccountRecord::create($rdata);
    }

    private function dikou_personal($order){
        $memberRep = new MemberRepository();
        $member  = $memberRep->getOne($order['uid']);

        if($order['original_price']){
            $total_price = $order['original_price'];
        }else{
            $total_price = $order['total_price'];
        }
        $member['account'] = str_replace(',', '', $member['account']);
        $dikou = get_dikou($member['account'], $total_price);
        if ($dikou) {
           $member->updateFields($order['uid'], ['account'=>bcsub($member['account'], $dikou,2)]);
        }
        return true;
    }

    private function insert_refund($order,$uid,$df_uid,$type){
        $memberRep = new MemberRepository();
        $account  = $memberRep->get_account($order['uid']);

        if($order['original_price']){
            $total_price = $order['original_price'];
        }else{
            $total_price = $order['total_price'];
        }

        $dikou = get_dikou($account,$total_price);
        if ($dikou && $dikou!='0.00') {
            $mm = $memberRep->getOne($uid);

            //记录
            $rdata['uid'] = $uid;
            $rdata['unionid'] = $mm['unionid'];
            $rdata['df_uid'] = $df_uid;
            $rdata['type'] = $type;
            $rdata['orderid'] = $order['id'];
            $rdata['inout'] = 0;
            $rdata['amount'] = $dikou;
            $rdata['remaining'] = str_replace(',', '', $mm['account']);//账户剩余

            AccountRecord::create($rdata);
        }
    }

    //更新互选池管理员账号
    private function _update_parter_income($order){
        // DB::beginTransaction();

        //充值 到谁的账户看会员的来源（互选池  分享）
        $elect_pool_id = MemberRecommend::where(['from' => "pool", 'uid' => $order['uid'] ])->value("ruid");

        $is_distribute = false;
        // 直接从互选池来的
        if(!$elect_pool_id) {  //寻找二级分销
            $ruid = MemberRecommend::where(['uid' => $order['uid'] ])->whereIn("from", ['h5','weapp'])->value("ruid");
            $elect_pool_id = MemberRecommend::where(['from' => "pool", "uid" => $ruid])->value("ruid");

            if(!$elect_pool_id) return false;
            $is_distribute = true;
        }

        $owner_uid = ElectPool::where("id", "=", $elect_pool_id)->value("owner_uid");
        if(empty($owner_uid)) return false;

        $parter = Parter::where("id", "=", $owner_uid)->first();
        if(empty($parter)) return false;

        // 判断订单是否已经添加了
        if(ParterIncome::where(['order_id' => $order['id'], 'parter_id' => $parter['id']])->count("id")){
            // DB::commit();
            return $is_distribute;
        }

        $rank = ($is_distribute == true)? $parter['second_award_rank'] : $parter['first_award_rank'];  //占比
        $fact_price = $order['total_price'] * $rank;

        $p_data['balance'] = $parter['balance'] + $fact_price;
        $p_data['total_account'] =  $parter['total_account'] + $fact_price;
        Parter::where("id","=",$parter['id'])->update($p_data);

        //增加收入记录
        ParterIncome::insert([
            'parter_id'         => $parter['id'],
            'uid'               => $order['uid'],
            'price'             => $fact_price,
            'ratio'             => $rank,
            'total_price'       => $order['total_price'],
            'object_type'       => $is_distribute ? "recharge2" : "recharge",
            'order_id'          => $order['id'],
            'balance'           => $p_data['balance'],
            'create_time'       => date("Y-m-d H:i:s")
        ]);

        return $is_distribute;
    }

}